package org.jeecgframework.web.material.service.impl;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.jeecgframework.web.material.service.OrderInfoServiceI;
import org.jeecgframework.web.material.service.OrderProcessServiceI;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
<<<<<<< HEAD
=======
import org.jeecgframework.web.material.entity.CustomerEntity;
import org.jeecgframework.web.material.entity.FlowDetailIncomeEntity;
import org.jeecgframework.web.material.entity.FlowEntity;
>>>>>>> a9c7731b4788b28c37d962faa7843e2cac438e61
import org.jeecgframework.web.material.entity.OrderFormEntity;
import org.jeecgframework.web.material.entity.OrderInfoEntity;
import org.jeecgframework.web.material.entity.OrderInstallEntity;
import org.jeecgframework.web.material.entity.OrderMeasureEntity;
import org.jeecgframework.web.material.entity.OrderProcessEntity;
import org.jeecgframework.web.material.entity.OrderProductEntity;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

<<<<<<< HEAD
=======
import java.text.SimpleDateFormat;
>>>>>>> a9c7731b4788b28c37d962faa7843e2cac438e61
import java.util.List;

import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;

import java.util.ArrayList;
<<<<<<< HEAD
=======
import java.util.Date;
>>>>>>> a9c7731b4788b28c37d962faa7843e2cac438e61
import java.util.UUID;
import java.io.Serializable;

@Service("orderInfoService")
@Transactional
public class OrderInfoServiceImpl extends CommonServiceImpl implements
		OrderInfoServiceI {
	/**
	 * 流程
	 * */
	@Autowired
	private OrderProcessServiceI orderProcessService;

	@Autowired
	private RuntimeService runtimeService;

	public <T> void delete(T entity) {
		super.delete(entity);
		// 执行删除操作配置的sql增强
		this.doDelSql((OrderInfoEntity) entity);
	}

	public void addMain(OrderInfoEntity orderInfo,
			List<OrderProductEntity> orderProductList) {
		// 保存主信息
		orderInfo.setIsSubmit("0");
		this.save(orderInfo);

		/** 保存-xdkj */
		for (OrderProductEntity orderProduct : orderProductList) {
			// 外键设置
			orderProduct.setOrderId(orderInfo);
			this.save(orderProduct);
		}
		// 执行新增操作配置的sql增强
		this.doAddSql(orderInfo);
	}

	public void updateMain(OrderInfoEntity orderInfo,
			List<OrderProductEntity> orderProductList) {
		// 保存主表信息
		orderInfo.setIsSubmit("0");
		this.saveOrUpdate(orderInfo);
		// ===================================================================================
		// 获取参数
		Object id0 = orderInfo.getId();
		// ===================================================================================
		// 1.查询出数据库的明细数据-xdkj
		String hql0 = "from OrderProductEntity where 1 = 1 AND oRDER_ID = ? ";
		List<OrderProductEntity> orderProductOldList = this.findHql(hql0, id0);
		// 2.筛选更新明细数据-xdkj
		for (OrderProductEntity oldE : orderProductOldList) {
			boolean isUpdate = false;
			for (OrderProductEntity sendE : orderProductList) {
				// 需要更新的明细数据-xdkj
				if (oldE.getId().equals(sendE.getId())) {
					try {
						MyBeanUtils.copyBeanNotNull2Bean(sendE, oldE);
						this.saveOrUpdate(oldE);
					} catch (Exception e) {
						e.printStackTrace();
						throw new BusinessException(e.getMessage());
					}
					isUpdate = true;
					break;
				}
			}
			if (!isUpdate) {
				// 如果数据库存在的明细，前台没有传递过来则是删除-xdkj
				super.delete(oldE);
			}

		}
		// 3.持久化新增的数据-xdkj
		for (OrderProductEntity orderProduct : orderProductList) {
			if (oConvertUtils.isEmpty(orderProduct.getId())) {
				// 外键设置
				orderProduct.setOrderId(orderInfo);
				this.save(orderProduct);
			}
		}
		// 执行更新操作配置的sql增强
		this.doUpdateSql(orderInfo);
	}

	/**
	 * 修改一对多,尺寸测量
	 * 
	 */
	public void updateMeasure(OrderInfoEntity orderInfo,
			List<OrderMeasureEntity> orderMeasureList) {
		// 保存主表信息
//		orderInfo.setIsSubmit("0");
//		this.getEntity(OrderInfoEntity.class, orderInfo.getId());
//		this.saveOrUpdate(orderInfo);
		// ===================================================================================
		// 获取参数
		Object id0 = orderInfo.getId();
		// ===================================================================================
		// 1.查询出数据库的明细数据-xdkj
		String hql0 = "from OrderMeasureEntity where 1 = 1 AND oRDER_ID = ? ";
		List<OrderMeasureEntity> orderMeasureOldList = this.findHql(hql0, id0);
		// 2.筛选更新明细数据-xdkj
		for (OrderMeasureEntity oldE : orderMeasureOldList) {
			boolean isUpdate = false;
			for (OrderMeasureEntity sendE : orderMeasureList) {
				// 需要更新的明细数据-xdkj
				if (oldE.getId().equals(sendE.getId())) {
					try {
						MyBeanUtils.copyBeanNotNull2Bean(sendE, oldE);
						this.saveOrUpdate(oldE);
					} catch (Exception e) {
						e.printStackTrace();
						throw new BusinessException(e.getMessage());
					}
					isUpdate = true;
					break;
				}
			}
			if (!isUpdate) {
				// 如果数据库存在的明细，前台没有传递过来则是删除-xdkj
				super.delete(oldE);
			}

		}
		// 3.持久化新增的数据-xdkj
		for (OrderMeasureEntity orderMeasure : orderMeasureList) {
			if (oConvertUtils.isEmpty(orderMeasure.getId())) {
				// 外键设置
				orderMeasure.setOrderId(orderInfo);
				this.save(orderMeasure);
			}
		}
		// 执行更新操作配置的sql增强
		this.doUpdateSql(orderInfo);
	}

	
	/**
	 * 修改一对多,尺寸测量
	 * 
	 */
	public void updateInstall(OrderInfoEntity orderInfo,
			List<OrderInstallEntity> orderInstallList) {
		// 保存主表信息
//		orderInfo.setIsSubmit("1");
//		this.saveOrUpdate(orderInfo);
		// ===================================================================================
		// 获取参数
		Object id0 = orderInfo.getId();
		// ===================================================================================
		// 1.查询出数据库的明细数据-xdkj
		String hql0 = "from OrderInstallEntity where 1 = 1 AND oRDER_ID = ? ";
		List<OrderInstallEntity> orderMeasureOldList = this.findHql(hql0, id0);
		// 2.筛选更新明细数据-xdkj
		for (OrderInstallEntity oldE : orderMeasureOldList) {
			boolean isUpdate = false;
			for (OrderInstallEntity sendE : orderInstallList) {
				// 需要更新的明细数据-xdkj
				if (oldE.getId().equals(sendE.getId())) {
					try {
						MyBeanUtils.copyBeanNotNull2Bean(sendE, oldE);
						this.saveOrUpdate(oldE);
					} catch (Exception e) {
						e.printStackTrace();
						throw new BusinessException(e.getMessage());
					}
					isUpdate = true;
					break;
				}
			}
			if (!isUpdate) {
				// 如果数据库存在的明细，前台没有传递过来则是删除-xdkj
				super.delete(oldE);
			}

		}
		// 3.持久化新增的数据-xdkj
		for (OrderInstallEntity orderInstall : orderInstallList) {
			if (oConvertUtils.isEmpty(orderInstall.getId())) {
				// 外键设置
				orderInstall.setOrderId(orderInfo);
				this.save(orderInstall);
			}
		}
		// 执行更新操作配置的sql增强
		this.doUpdateSql(orderInfo);
		String hql1 = "from OrderProductEntity where 1 = 1 AND oRDER_ID = ? ";
		
		List<OrderProductEntity> orderProduct = this.findHql(hql1, orderInfo.getId());
		// 2.筛选更新明细数据-xdkj
		for (OrderProductEntity entity : orderProduct) {   
			String hql2 = "from OrderProcessEntity where 1 = 1 AND oRDER_product_ID = ? ";
			
			List<OrderProcessEntity> processList = this.findHql(hql2, entity.getId());
			if(processList.size()>0){
				// 安装人员安排
				String instanceId = processList.get(0).getInstanceId();
				Execution execution = runtimeService.createExecutionQuery()
						.processInstanceId(instanceId).singleResult();
				ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(instanceId).active().singleResult();
				if (instance!=null
					&&"arrangeInstaller".equals(instance.getActivityId())) {
					List<String> userList = listInstallerUser(entity.getOrderId().getId().toString());
					// 发送通知
					if (userList.size() > 0) {
						runtimeService.setVariable(instanceId, "installUser", userList);
						runtimeService.signal(instanceId);
					}

				}
			}
		}
		
		
	}
	
	/**
	 * 获取安装人员.
	 */
	public List<String> listInstallerUser(String orderId) {

		List<String> users = new ArrayList<String>();
		// ===================================================================================
		// 删除-xdkj
		String hql0 = "from OrderInstallEntity where 1 = 1 AND oRDER_ID = ? ";
		List<OrderInstallEntity> orderInstallEntityList = this.findHql(hql0,
				orderId);
		for (OrderInstallEntity entity : orderInstallEntityList) {
			users.add(entity.getEngineerId().getId().toString());
		}
		return users;
	}

	public void delMain(OrderInfoEntity orderInfo) {
		// 删除主表信息
		this.delete(orderInfo);
		// ===================================================================================
		// 获取参数
		Object id0 = orderInfo.getId();
		// ===================================================================================
		// 删除-xdkj
		String hql0 = "from OrderProductEntity where 1 = 1 AND oRDER_ID = ? ";
		List<OrderProductEntity> orderProductOldList = this.findHql(hql0, id0);
		this.deleteAllEntitie(orderProductOldList);
	}

	/**
	 * 订单信息提交.
	 * */
	public void isSubmit(OrderInfoEntity orderInfo) {
		// 保存主表信息
<<<<<<< HEAD
		orderInfo.setIsSubmit("1");
		this.saveOrUpdate(orderInfo);
=======
		OrderInfoEntity order = getEntity(OrderInfoEntity.class, orderInfo.getId());
		orderInfo.setIsSubmit("1");
		this.saveOrUpdate(order);
		// 当前用户
		TSUser user = ResourceUtil.getSessionUserName();
		
		//保存订单主财务付款信息
		FlowEntity  flow = new FlowEntity();
		flow.setOrderId(order.getId().toString());
		flow.setTotal(Double.parseDouble(order.getTotalPrice()));
		flow.setPaid(Double.parseDouble(order.getDownPayment()));
		flow.setPaidProgress("1");
		flow.setCompanyId(user.getCompany());
		this.saveOrUpdate(flow);
		//保存收入信息
		FlowDetailIncomeEntity come= new FlowDetailIncomeEntity();
		come.setFlowId(flow);
		come.setMoney(flow.getPaid());
		come.setPayerId(user.getId());
		come.setPayerName(user.getUserName());
		come.setTradeTime(new Date());
		come.setCompanyId(user.getCompany());
		come.setReceiverId("0");
		come.setReceiverName(orderInfo.getUserName());
		this.saveOrUpdate(come);
		//保存客户信息
		CustomerEntity customer = new CustomerEntity();
		customer.setRealName(orderInfo.getUserName());
		customer.setUserName(orderInfo.getUserTelephone1());
		customer.setPassword(orderInfo.getUserTelephone1());
		customer.setAddress(orderInfo.getUserAddress());
		customer.setCompany(user.getCompany());
		customer.setCreateDate(new Date());
		this.saveOrUpdate(customer);
>>>>>>> a9c7731b4788b28c37d962faa7843e2cac438e61
		// this.delete(orderInfo);
		// ===================================================================================
		// 获取参数
		Object id0 = orderInfo.getId();
		// ===================================================================================
		// 删除-xdkj
		String hql0 = "from OrderProductEntity where 1 = 1 AND oRDER_ID = ? ";
		List<OrderProductEntity> orderProductOldList = this.findHql(hql0, id0);
<<<<<<< HEAD
		// 当前用户
		TSUser user = ResourceUtil.getSessionUserName();
=======
	
>>>>>>> a9c7731b4788b28c37d962faa7843e2cac438e61
		//
		orderProcessService.processWorkFlowStart(orderProductOldList);

	}

	/**
	 * 測量人是否存在.
	 */
	public  boolean isExist(OrderInfoEntity orderInfo) {

		// 获取参数
		Object id0 = orderInfo.getId();
		// ===================================================================================
		// 删除-xdkj
		String hql0 = "from OrderMeasureEntity where 1 = 1 AND oRDER_ID = ? ";
		List<OrderMeasureEntity> orderMeasureEntityList = this.findHql(hql0,
				id0);
		if(orderMeasureEntityList.size()>0){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 默认按钮-sql增强-新增操作
	 * 
	 * @param id
	 * @return
	 */
	public boolean doAddSql(OrderInfoEntity t) {
		return true;
	}

	/**
	 * 默认按钮-sql增强-更新操作
	 * 
	 * @param id
	 * @return
	 */
	public boolean doUpdateSql(OrderInfoEntity t) {
		return true;
	}

	/**
	 * 默认按钮-sql增强-删除操作
	 * 
	 * @param id
	 * @return
	 */
	public boolean doDelSql(OrderInfoEntity t) {
		return true;
	}

	/**
	 * 替换sql中的变量
	 * 
	 * @param sql
	 * @return
	 */
	public String replaceVal(String sql, OrderInfoEntity t) {
		sql = sql.replace("#{id}", String.valueOf(t.getId()));
		sql = sql.replace("#{user_id}", String.valueOf(t.getUserId()));
		sql = sql.replace("#{user_name}", String.valueOf(t.getUserName()));
		sql = sql
				.replace("#{user_address}", String.valueOf(t.getUserAddress()));
		sql = sql.replace("#{user_telephone_1}",
				String.valueOf(t.getUserTelephone1()));
		sql = sql.replace("#{user_telephone_2}",
				String.valueOf(t.getUserTelephone2()));
		sql = sql.replace("#{company_id}", String.valueOf(t.getCompanyId()));
		sql = sql.replace("#{user_telephone_3}",
				String.valueOf(t.getUserTelephone3()));
		sql = sql.replace("#{remark}", String.valueOf(t.getRemark()));
		sql = sql.replace("#{is_common}", String.valueOf(t.getIsCommon()));
		sql = sql.replace("#{is_continue}", String.valueOf(t.getIsContinue()));
		sql = sql.replace("#{UUID}", UUID.randomUUID().toString());
		return sql;
	}
}